<template>
    <div>
        <a-modal v-model:open="open" title="员工导入" footer>
            <a-upload-dragger :showUploadList="false" name="file" :multiple="true" @change="handleChange">
                <p class="ant-upload-drag-icon">
                    <InboxOutlined></InboxOutlined>
                </p>
                <div class="ant-upload-text" @click="downloadfile($event)">下载导入模板</div>
                <p class="ant-upload-hint">
                    将文件拖到此处 <span class="upload-span">点击上传</span>
                </p>
            </a-upload-dragger>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { InboxOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadChangeParam } from 'ant-design-vue';
import { getSysUserImportTemplateApi, postSysUserImportApi } from '@/common/apis/information'
import { saveAs } from 'file-saver';
import { debounce } from 'lodash';


const open = ref<boolean>(false);

const props = defineProps({
    getSysUserData: {
        type: Function,
        required: true,
    },
})


// 点击下载导入模板
const downloadfile = async (event) => {
    event.stopPropagation(); // 阻止事件冒泡
    try {
        const result = await getSysUserImportTemplateApi();
        console.log(result, 'result');
        // 创建 Blob 对象
        const blob = new Blob([result.data], { type: result.data.type });
        // 使用 file-saver 保存文件
        saveAs(blob, '员工信息表.xlsx');
    } catch (error) {
        console.error('文件下载失败', error);
        alert('文件下载失败，请重试或联系管理员。');
    }
};

const showModal = () => {
    open.value = true;
};

// 上传文件  定义防抖函数，延迟 300ms
const debouncedHandleChange = debounce(async (info) => {
    if (info.file && info.file.originFileObj) {
        const formData = new FormData();
        formData.append('file', info.file.originFileObj);

        try {
            // 调用上传接口
            const response = await postSysUserImportApi(formData);
            console.log(response, 'response')

            // 检查上传是否成功
            if (response.data.success) {
                message.success('数据上传成功');
                // 刷新员工列表
                await props.getSysUserData();
                // 关闭弹框
                open.value = false;
            } else {
                // 上传失败，展示错误信息
                message.error(response.data.message || '上传失败，请检查文件内容');
            }
        } catch (error) {
            // 处理请求异常
            message.error('上传失败，请稍后重试');
            console.error('上传失败:', error);
        }
    }
}, 300);

// 在事件绑定中使用防抖函数
const handleChange = (info: UploadChangeParam) => {
    debouncedHandleChange(info);
};


defineExpose({
    showModal
})
</script>



<style lang="scss" scoped>
.ant-upload-text {
    color: #71acff;
}

.upload-span {
    color: #71acff;
}
</style>